package com.monkeygroup.mygoplus.view.home.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.utils.image.Images;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.http.ThingsHttpModel;
import com.monkeygroup.mygoplus.thing.vo.BuildingVo;
import com.monkeygroup.mygoplus.thing.vo.MyImageVO;
import com.monkeygroup.mygoplus.thing.vo.UserVO;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by LCW on 2017/5/31.
 */

public class BuildingDetailActivity extends BaseActivity implements OnMapReadyCallback {

    private TextView txtTitle, txtImgSize, txtPurpose, txtName, txtRoomarea, txtAddr,txtShape,txtCompany,txtCompletedate,
            txtUnitprice, txtArea, txtStorey, txtTotalprice,  txtType, txtAddr1,txtAddr2,txtMethod,txtTotalrooms,txtPostulate,
            txtStatname, txtBalconys, txtRooms, txtToilets, txtHalls,txtProportion,txtFee,txtCartport,txtPrice,txtContact;
    private CheckOverSizeTextView text_things_detail_desc;
    private LinearLayout linearLayoutThingsDescOpen,linearLayoutThingsDescClose;
    private Button btnThingsOpenTextOpen,btnThingsOpenTextClose;
    private List<MyImageVO> imageVO;
    private BuildingVo propertyModel;
    private UserVO userVO;
    //請求
    private ThingsHttpModel httpThingsModel;

    private LayoutInflater mInflater;
    private LinearLayout linearLayoutThingsMap;

    private LinearLayout linear;

    private ViewPager viewPager;
    private SimpleDraweeView[] mImageViews;
    private SimpleDraweeView imgCover;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_building_detail);
        mInflater = LayoutInflater.from(this);
    }

    @Override
    public void initView() {
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("新建案");
        txtImgSize = (TextView) findViewById(R.id.viewPager_things_all);
        txtPurpose = (TextView) findViewById(R.id.text_things_detail_purpose);
        txtName = (TextView) findViewById(R.id.text_things_detail_name);
        txtContact = (TextView) findViewById(R.id.text_detail_contact);
        txtRoomarea = (TextView) findViewById(R.id.text_building_detail_roomarea);
        txtUnitprice = (TextView) findViewById(R.id.text_building_detail_unitprice);
        txtTotalprice = (TextView) findViewById(R.id.text_building_detail_totalprice);
        txtAddr1 = (TextView) findViewById(R.id.text_building_detail_addr1);
        txtAddr2 = (TextView) findViewById(R.id.text_building_detail_addr2);
        txtType = (TextView) findViewById(R.id.text_building_detail_type);
        txtShape = (TextView) findViewById(R.id.text_building_detail_shape);
        txtCompany= (TextView) findViewById(R.id.text_building_detail_company);
        txtMethod = (TextView) findViewById(R.id.text_building_detail_method);
        txtStatname = (TextView) findViewById(R.id.text_building_detail_statname);
        txtCompletedate = (TextView) findViewById(R.id.text_building_detail_completedate);
        txtTotalrooms = (TextView) findViewById(R.id.text_things_detail_totalrooms);
        txtProportion = (TextView) findViewById(R.id.text_building_detail_proportion);
        txtStorey = (TextView) findViewById(R.id.text_building_detail_storey);
        txtPostulate = (TextView) findViewById(R.id.text_building_detail_postulate);
        txtFee = (TextView) findViewById(R.id.text_building_detail_fee);
        txtCartport = (TextView) findViewById(R.id.text_building_detail_cartport);
        txtAddr = (TextView) findViewById(R.id.text_detail_addr);
        imgCover = (SimpleDraweeView) findViewById(R.id.img_building_cover);
        txtArea = (TextView) findViewById(R.id.text_building_detail_area);
        txtPrice = (TextView) findViewById(R.id.text_building_detail_price);


        txtBalconys = (TextView) findViewById(R.id.text_things_detail_balconys);
        txtRooms = (TextView) findViewById(R.id.text_things_detail_rooms);
        txtToilets = (TextView) findViewById(R.id.text_things_detail_toilets);
        txtHalls = (TextView) findViewById(R.id.text_things_detail_halls);
        text_things_detail_desc = (CheckOverSizeTextView) findViewById(R.id.text_things_detail_desc);
        btnThingsOpenTextOpen = (Button) findViewById(R.id.btn_things_open_text_open);
        linearLayoutThingsDescOpen = (LinearLayout) findViewById(R.id.linearLayout_things_desc_open);
        btnThingsOpenTextClose = (Button) findViewById(R.id.btn_things_open_text_close);
        linearLayoutThingsDescClose = (LinearLayout) findViewById(R.id.linearLayout_things_desc_close);
        linear = (LinearLayout) this.findViewById(R.id.linearlayout_things_scrollView);
        linearLayoutThingsMap = (LinearLayout) findViewById(R.id.linearLayout_things_map);

        imageVO = (List<MyImageVO>) getIntent().getBundleExtra("param").getSerializable("imgModel");
        propertyModel = (BuildingVo) getIntent().getBundleExtra("param").getSerializable("propertyModel");
        userVO = (UserVO) getIntent().getBundleExtra("param").getSerializable("userVO");
        setImage(imageVO);
        setThingsInfo(propertyModel);
        setUserInfo(userVO);

        String param = "?area="+propertyModel.getArea();
        initHorizontalScrollViewRequest(param);
        httpThingsModel.requestThings();

        text_things_detail_desc.setOnOverLineChangedListener(new CheckOverSizeTextView.OnOverSizeChangedListener() {
            @Override
            public void onChanged(boolean isOverSize) {
                if(isOverSize){
                    text_things_detail_desc.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
                    linearLayoutThingsDescOpen.setVisibility(View.VISIBLE);
                }
            }
        });
        btnThingsOpenTextOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(text_things_detail_desc.isOverSize()){
                    text_things_detail_desc.displayAll();
                    linearLayoutThingsDescOpen.setVisibility(View.GONE);
                    linearLayoutThingsDescClose.setVisibility(View.VISIBLE);
                }else{
                    text_things_detail_desc.hide(15);
                }
            }
        });
        btnThingsOpenTextClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(text_things_detail_desc.isOverSize()){
                    text_things_detail_desc.displayAll();
                }else{
                    text_things_detail_desc.hide(15);
                    linearLayoutThingsDescOpen.setVisibility(View.VISIBLE);
                    linearLayoutThingsDescClose.setVisibility(View.GONE);
                }
            }
        });

        initMap();
    }

    @Override
    public void setListener() {

    }

    @Override
    public void doEvent() {

    }

    private void setImage(List<MyImageVO> imgModel) {
        List<String> imgs = new ArrayList<>();
        for (MyImageVO vo : imgModel) {
            if (vo.getCover() != 1) {
                imgs.add(vo.getPath8());
            }
        }
        viewPager = (ViewPager) findViewById(R.id.viewPager_things_all_img);
        mImageViews = new SimpleDraweeView[imgs.size()];
        for (int i = 0; i < imgs.size(); i++) {
            final SimpleDraweeView imageView = new SimpleDraweeView(this);
            mImageViews[i] = imageView;
            Images.with(this).load(Uri.parse(imgs.get(i).toString())).into(imageView);
        }

        viewPager.setAdapter(new MyAdapter());
        if(mImageViews.length==0){
            txtImgSize.setText(0 + "/" + mImageViews.length);
        }else{
            txtImgSize.setText(1 + "/" + mImageViews.length);
        }
        viewPager.setCurrentItem(0);
        viewpagerListener();
        //设置ViewPager的默认项, 设置为长度的100倍，这样子开始就能往左滑动  
        //viewPager.setCurrentItem((mImageViews.length)*100);
    }

    private void viewpagerListener() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                txtImgSize.setText((arg0 + 1) + "/" + mImageViews.length);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    class MyAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return mImageViews.length;
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(mImageViews[position % mImageViews.length]);
        }

        /**
         * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
         */
        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(mImageViews[position % mImageViews.length], 0);
            return mImageViews[position % mImageViews.length];
        }

    }

    private void setThingsInfo(BuildingVo propertyModel) {
        txtPurpose.setText("新建案");
        txtName.setText(propertyModel.getName());
        txtAddr.setText(propertyModel.getAddr());
        txtRoomarea.setText(propertyModel.getRoomarea1()+"~"+propertyModel.getRoomarea2()+"坪");
        txtShape.setText(propertyModel.getShape());
        txtCompany.setText(propertyModel.getCompany());
        txtCompletedate.setText(propertyModel.getCompletedate());
        txtUnitprice.setText("NT$"+propertyModel.getUnitprice1()+"~"+propertyModel.getUnitprice2()+"萬元/坪");
        txtTotalprice.setText("NT$"+propertyModel.getTotalprice1()+"~"+propertyModel.getTotalprice2()+"萬元");
        txtAddr1.setText(propertyModel.getAddr());
        txtAddr2.setText(propertyModel.getAddr());
        txtMethod.setText(propertyModel.getMethod());
        txtTotalrooms.setText(propertyModel.getTotalrooms());
        txtPostulate.setText(String.valueOf(propertyModel.getPostulate()));
        txtStatname.setText(propertyModel.getStatname());
        txtProportion.setText(String.valueOf(propertyModel.getProportion()));
        txtFee.setText(propertyModel.getFee());
        txtCartport.setText(propertyModel.getCartport());
        //txtPrice.setText(propertyModel.getPrice());
        txtArea.setText(propertyModel.getArea() + " 坪");
        txtStorey.setText(propertyModel.getStorey());
        txtType.setText(propertyModel.getType());
        //txtBalconys.setText(propertyModel.getBalconys() + "陽臺");
        //txtRooms.setText(propertyModel.getRooms() + "房");
        //txtToilets.setText(propertyModel.getToilets() + "衛浴");
        //txtHalls.setText(propertyModel.getHalls() + "聼");

        text_things_detail_desc.setText(propertyModel.getDesc());
    }

    private void setUserInfo(UserVO userVO) {
        txtContact.setText(userVO.getName() + " " + userVO.getTel());
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        LatLng positon = new LatLng(propertyModel.getLat(), propertyModel.getLng());
        googleMap.addMarker(new MarkerOptions().position(positon).title(""));
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(positon));
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("positon", propertyModel.getLat()+"-"+propertyModel.getLng());
                Intent intent = new Intent(BuildingDetailActivity.this,MapActivity.class);
                intent.putExtra("positon",bundle);
                startActivityForResult(intent,1);
            }
        });
    }

    private void initMap(){
        View view = mInflater.inflate(R.layout.map_things_detail,linearLayoutThingsMap, false);
        linearLayoutThingsMap.addView(view);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map_thing_detail);
        mapFragment.getMapAsync(this);
    }

    public void initHorizontalScrollViewRequest(String param) {
        httpThingsModel = new ThingsHttpModel(RequestUrl.buildingUrl + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<BuildingVo> propertys = gson.fromJson(gson.toJson(building), new TypeToken<List<BuildingVo>>() {
                        }.getType());

                        for (int i = 0; i < propertys.size(); i++) {
                            if(propertys.get(i).getSeq()==propertyModel.getSeq()){
                                continue;
                            }
                            createChildLinearLayout(propertys.get(i),i);
                        }
                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);
    }

    private void createChildLinearLayout(final BuildingVo vo, final int i) {
        View view = mInflater.inflate(R.layout.item_things_detail_horizontalscrollview,linear, false);
        SimpleDraweeView imgView = (SimpleDraweeView) view.findViewById(R.id.img_things_horizontalscrollview);
        //Images.with(this).load(Uri.parse(vo.getImg())).resize(180,180).into(imgView);
        TextView text1 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_1);
        text1.setText(vo.getName());
        TextView text2 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_2);
        //text2.setText("NT$ "+vo.getSaleprice()+"/萬");
        TextView text3 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_3);
        //text3.setText("坪數:"+vo.getLawnarea()+" 坪");
        TextView text4 = (TextView) view.findViewById(R.id.text_things_horizontalscrollview_4);
        text4.setText("層樓:"+vo.getStorey());
        linear.addView(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String param ="?seq="+vo.getSeq();
                initDetailRequest(param);
                httpThingsModel.requestThings();
            }
        });
    }

    public void initDetailRequest(String param) {
        httpThingsModel = new ThingsHttpModel(RequestUrl.getbuilding + param,
                new ThingsHttpModel.SimpleOnHttpRequestListener() {
                    @Override
                    public void onRequestFinished(String resultCode, Integer timestamp) {

                    }

                    @Override
                    public void onRequestFinished(String resultCode, Object property, Object user, Object users, Object circuit, Object img) {

                    }

                    @Override
                    public void onBuildingRequestFinished(String resultCode, Object building, Object user, Object users, Object circuit, Object img) {
                        Gson gson = new Gson();
                        List<MyImageVO> imgModel = gson.fromJson(gson.toJson(img), new TypeToken<List<MyImageVO>>() {
                        }.getType());
                        BuildingVo propertyModel = gson.fromJson(gson.toJson(building), new TypeToken<BuildingVo>() {
                        }.getType());
                        UserVO userVO = gson.fromJson(gson.toJson(user), new TypeToken<UserVO>() {
                        }.getType());

                        Bundle bundle = new Bundle();
                        bundle.putSerializable("imgModel", (Serializable) imgModel);
                        bundle.putSerializable("propertyModel", propertyModel);
                        bundle.putSerializable("userVO", userVO);
                        Intent intent = new Intent(BuildingDetailActivity.this,BuildingDetailActivity.class);
                        intent.putExtra("param", bundle);
                        BuildingDetailActivity.this.startActivityForResult(intent, 3);
                    }

                    @Override
                    public void onCommunityRequestFinished(String resultCode, Object community, Object user, Object users, Object circuit, Object img) {

                    }
                }, true);
    }

}